<template>
  <el-dialog v-model="dialogVisible" title="菜单/按钮权限绑定" width="40%" @close="handleClose">
    <el-button type="primary" @click="saveUserPermission">保存</el-button>
    <el-scrollbar style="height: 400px">
      <el-tree
        ref="permissionTreeRef"
        :data="menuTreeList"
        show-checkbox
        default-expand-all
        node-key="id"
        :props="{ label: 'title', children: 'children' }"
      />
    </el-scrollbar>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, nextTick } from 'vue'
import { ElMessage, ElTree } from 'element-plus'
import { menuTreeListApi } from '@/api/menu'
import { userBindMenuApi, getUserBindMenuInfoApi } from '@/api/user'

const dialogVisible = ref(false)
/**
 * 获取menu树列表
 */
const menuTreeList = ref()
const getMenuTreeList = async () => {
  try {
    const { code, data } = await menuTreeListApi()
    if (code === 0) {
      menuTreeList.value = data ?? []
    }
  } catch (error) {
    console.log(error)
  }
}
/**
 * 用户权限回显、保存
 */
const permissionTreeRef = ref<InstanceType<typeof ElTree>>()
const setSelectedTreeItem = async rowItem => {
  const { code, data } = await getUserBindMenuInfoApi(rowItem.id)
  if (code === 0) {
    permissionTreeRef.value?.setCheckedKeys(data ?? [])
  }
}
const saveUserPermission = async () => {
  try {
    const params = {
      id: userId.value,
      menuIds: permissionTreeRef.value?.getCheckedKeys()
    }
    const { code } = await userBindMenuApi(params)
    if (code === 0) {
      ElMessage.success('保存成功')
    }
  } catch (error) {
    console.log(error)
  }
}
/**
 * 打开/关闭弹窗
 */
const userId = ref()
const handleOpen = async rowItem => {
  userId.value = rowItem.id
  await getMenuTreeList()
  dialogVisible.value = true
  await nextTick()
  await setSelectedTreeItem(rowItem)
}
const handleClose = () => {
  userId.value = null
  dialogVisible.value = false
}
defineExpose({ handleOpen })
</script>
<style scoped>
.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>
